<?php
namespace App\Http\Controllers\Api\Promotion;

use Carbon\Carbon;

use App\Models\Bill\Bill;

use Illuminate\Http\Request;

use App\Models\Activity\Presale;//商品预售主表

use App\Models\Mall\MallGroup;//门店组表

use App\Models\Goods\GoodsSale;//销售商品表

use App\Http\Controllers\Controller;

use App\Models\Goods\GoodsStore;//库存表

use App\Models\ConfigureFunction;

use App\Models\Activity\PresaleDetail; //商品预售详情表

use Illuminate\Support\Facades\Redis as Redis;

class PreSaleController extends Controller
{

    /****
     * 查询预售活动
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function search(Request $request)
    {

        $mallID = $request->input('mallID',0);//门店ID
        $platform = $request->input('platform',6); //平台类型
        $session_id = $request->input('session_id',session_id());

        if ( $platform != 6 ) { //非小程序平台查询redis保存的门店ID

            $is_open_choose_mall = ConfigureFunction::getConfigureField(8,'is_open_choose_mall',1);//查询是否开启选店
            if ( $is_open_choose_mall ) {
                $choose_mall_id = redisTransformation( Redis::get($session_id.'G_CHOOSE_MALL_ID'));//获取选店ID
                if ( $choose_mall_id ) {
                    $mallID = $choose_mall_id;
                }
            }

        }

        //获取客户号
        $pcustID = get_customer_id($session_id, $platform);

        //是否开启门店选品
        $is_choose_goods_by_mall = ConfigureFunction::getConfigureField(8, 'is_choose_goods_by_mall',1);

        //获取redis缓存数据
        $pre_sale = Redis::get('WDH_PROMOTION_PRE_SALE') ;
        if ( !$pre_sale ) {

            $pre_sale = [
                'now_buy' => [],
                'next_buy' => [],
            ];

            //当前预售活动
            $pre_sale_now_data = Presale::select('presale_id','presale_name','presale_photo')
                ->where( [['start_time' , '<=' , Carbon::now()], ['end_time' , '>=' , Carbon::now()], ['useFlg' , 1]])->first();

            if ( !empty( $pre_sale_now_data ) ) {
                $pre_sale_now_data = collect($pre_sale_now_data)->toArray();
                $pre_sale['now_buy'] = $this->getDetail( $pre_sale_now_data );
            }

            //下期预售
            $pre_sale_next_data = Presale::select('presale_id','presale_name','presale_photo')
                ->where( [['start_time' , '>' , Carbon::now()], ['useFlg' , 1]])->first();

            if ( !empty( $pre_sale_next_data ) ) {
                $pre_sale_next_data = collect($pre_sale_next_data)->toArray();
                $pre_sale['next_buy'] = $this->getDetail( $pre_sale_next_data );
            }

            Redis::setex('WDH_PROMOTION_PRE_SALE', 3600, json_encode($pre_sale));

        } else {
            $pre_sale = json_decode($pre_sale,true);
        }

        /**
         * ========================
         *  处理商品数据
         * ========================
         */
        foreach( $pre_sale as $p=>&$pre ) {

            if ( empty($pre) ) {
                continue;
            }

            foreach ( $pre['goods'] as $g=>&$good ) { //循环商品

                //查询商品是否存在
                $goods_data = GoodsSale::getCache( $good['postID'] );
                if ( !$goods_data ) {
                    unset( $pre['goods'][$g] );
                    continue;
                }

                //查询所选门店是否在商品指定门店组里。如果商品没有指定门店组，则默认所有门店均售卖
                if ( $mallID > 0 && $good['mall_group_id'] > 0 ) {

                    $mall_group_data = MallGroup::getCache( $good['mall_group_id'] );
                    if ( !isset( $mall_group_data['map'][$mallID] ) ) {
                        unset( $pre['goods'][$g] );
                        continue;
                    }

                }

                $goods_status = 1 ;//商品预售未开始

                if ( $p == 'now_buy' ) {//当前预售

                    //实时查询已购买数量
                    $saled_amount = PresaleDetail::select('saled_amount')->where([['presale_id',$pre['pre_sale_id']],['postID',$good['postID']]])->first();

                    if ( $good['start_time'] > Carbon::now() ) { //未开始
                        $goods_status = 1; //未开始
                    } elseif ( $good['end_time'] < Carbon::now() ) { //已结束
                        $goods_status = 4; //已结束
                    } else { //进行中

                        //检查库存
                        if ( $is_choose_goods_by_mall ) {
                            $mall_store = GoodsStore::search($goods_data['product_code'], $goods_data['product_spec'], $mallID );
                        } else {
                            $mall_store = GoodsStore::search($goods_data['product_code'], $goods_data['product_spec']);
                        }

                        if ( $mall_store < $good['max_sale_amount'] ) {
                            $good['max_sale_amount'] = $mall_store;
                        }

                        if ( $good['max_sale_amount'] <= app_to_int($saled_amount->saled_amount) ) {
                            $goods_status = 3;  //进行中但已售完
                        } else {

                            $goods_status = 2;  //进行中
                            if ($pcustID) {

                                //统计当前用户购买这件商品的数量
                                $customer_max_buy_amount = Bill::join("bill_goods","bill_master.bill_no",'=','bill_goods.bill_no')
                                    ->where([
                                        ['bill_master.pcustID', $pcustID],
                                        ['bill_master.billType', 8],
                                        ['bill_master.bill_status', '<>', 5],
                                        ['bill_goods.goods_postID',$good['postID'] ]
                                    ])
                                    ->whereBetween('bill_master.createTime', [$good['start_time'],$good['end_time']])
                                    ->sum('bill_goods.goods_amount');

                                if ($customer_max_buy_amount && $customer_max_buy_amount >= $good['max_buy_amount']) {
                                    $goods_status = 5 ; //进行中但当前用户已超过最大购买数量
                                }

                            }

                        }

                    }

                }

                $good['goods_status'] = $goods_status;
                $good['start_time_stamp'] = strtotime($good['start_time']);
                $good['end_time_stamp'] = strtotime($good['end_time']);
                //剔除页面用不到的字段
                unset( $good['start_time'] );
                unset( $good['end_time'] );
                unset( $good['max_sale_amount'] );//预售总数量
                unset( $good['max_buy_amount'] );//用户最大预售数量
                unset( $good['mall_group_id'] ); //预售门店组id

            }

        }

        //返回数据
        $return_data = [
            'now_buy' => [  //当前预售
                'id' => $pre_sale['now_buy']['pre_sale_id'],
                'name' => $pre_sale['now_buy']['pre_sale_name'],
                'pic' => $pre_sale['now_buy']['pre_sale_photo'],
                'goods' => $pre_sale['now_buy']['goods'],
            ],
            'next_buy' => [ //下期预售
                'id' => $pre_sale['next_buy']['pre_sale_id'],
                'name' => $pre_sale['next_buy']['pre_sale_name'],
                'pic' => $pre_sale['next_buy']['pre_sale_photo'],
                'goods' => $pre_sale['next_buy']['goods'],
            ]
        ];

        return response()->json([ 'code' => 200 , 'message' => 'ok' , 'data' => $return_data ]);

    }

    /**
     * 获取预售活动详情
     * @param array $pre_sale_data
     * @return array
     */
    public function getDetail ($pre_sale_data)
    {
        $data = [
            'pre_sale_id' => app_to_int($pre_sale_data['presale_id']),
            'pre_sale_name' => $pre_sale_data['presale_name'],
            'pre_sale_photo' => $pre_sale_data['presale_photo'],
            'goods' => []
        ];

        //查询活动的商品
        $pre_sale_goods_data = PresaleDetail::where('presale_id',$data['pre_sale_id'])
            ->orderBy('sort', 'desc')
            ->get()
            ->toArray();

        if ( !$pre_sale_goods_data ) {
            return [];
        }

        foreach ( $pre_sale_goods_data as &$goods ) {

            $data['goods'][] = [
                'postID' => app_to_int($goods['postID']), //网购号
                'goods_name' => $goods['goodsName'], //商品名称
                'wap_link' => $goods['goodsLink'],  //商品链接
                'img_link' => $goods['picLink'], //图片链接
                'sale_price' => app_to_decimal($goods['salePrice']), //销售价格
                'pre_price' => app_to_decimal($goods['pre_price']), //预售价格
                'start_time' => $goods['startTime'],
                'end_time' => $goods['endTime'],
                'max_sale_amount' => app_to_int($goods['max_sale_amount']),  //预售总数量
                'max_buy_amount' => app_to_int($goods['max_buy_amount']), //用户最大预售数量
                'mall_group_id' => app_to_int($goods['mall_group_id']), //预售门店组id
            ];

        }

        return $data;

    }

}



